// 全部组件的通用数据处理逻辑 文件
import { setPx, getUrlParams, validatenull } from './util';
import config from './config';
import crypto from '@/utils/crypto';
import { funEval, uuid } from '@/utils/utils';
import COMMON from '@/config';
import { mapState, mapGetters } from 'vuex';
import axios from 'axios';
import { EventBus } from '@/utils/event-bus';
import { GzLog } from '@/utils/consoleLogButton.js';
import { Base64 } from 'js-base64';
export default (() => {
	return {
		inject: ['allCompContainer', 'container'],
		props: {
			eventParams: Function,
			stylesFormatter: Function,
			dataFormatter: [Function, Array],
			titleFormatter: Function,
			labelFormatter: Function,
			clickFormatter: Function,
			sqlFormatter: Function,
			formatter: Function,
			echartFormatter: Function,
			dataQuery: Function,
			dataHeader: Function,
			display: {
				type: Boolean,
				default: true
			},
			width: {
				type: [Number, String],
				default: 600
			},
			height: {
				type: [Number, String],
				default: 600
			},
			left: {
				type: [Number, String],
				default: 0
			},
			top: {
				type: [Number, String],
				default: 0
			},
			theme: {
				type: String
			},
			child: {
				type: Object,
				default: () => {
					return {};
				}
			},
			sql: {
				type: String
			},
			autoRequest: {
				type: Boolean,
				default: false
			},
			appendParams: {
				type: Boolean,
				default: false
			},
			dataFilter: {
				type: Boolean,
				default: false
			},
			time: {
				type: Number,
				default: 0
			},
			url: {
				type: String
			},
			disabled: {
				type: Boolean,
				default: true
			},
			dataType: {
				type: Number,
				default: 0
			},
			dataMethod: {
				type: String,
				default: 'get'
			},
			id: {
				type: String,
				default: 'main_' + uuid()
			},
			data: {
				type: [Object, String, Array]
			},
			component: {
				type: Object,
				default: () => {
					return {};
				}
			},
			option: {
				type: Object,
				default: () => {
					return {};
				}
			}
		},
		data() {
			return {
				contain: this.contain,
				container: this.container,
				oldApiParams: null,
				apiParams: null,
				queryParams: this.$route.query,
				oldSql: null, // sql字符串形式，不含sql.id
				sqlId: null,
				dynamicQuery: {},
				propQuery: {},
				headerHeight: '',
				checkChart: '',
				myChart: '',
				dataChart: [],
				dataAxios: {},
				dataUrl: '',
				key: false,
				isChart: false,
				isHighChart: false,
				styles: {},
				appendCheck: {},
				appendObj: {},
				appendList: [],
				className: ''
			};
		},
		watch: {
			dataAppend(val) {
				this.appendObj = {};
				this.appendList = [];
				if (!val) {
					this.appendCheck = clearInterval(this.appendCheck);
				} else {
					this.dataChart = [];
				}
				this.updateData();
			},
			echartFormatter() {
				this.updateChart && this.updateChart();
			},
			url: {
				handler(val) {
					this.dataUrl = val || '';
				},
				deep: true,
				immediate: true
			},
			data: {
				handler() {
					this.updateData();
				},
				deep: true,
				immediate: true
			},
			width() {
				this.updateData();
			},
			height() {
				this.updateData();
			},
			theme() {
				this.myChart.dispose();
				this.init();
				this.updateData();
			},
			option: {
				handler() {
					if (this.myChart && this.isChart) {
						this.updateData();
					}
					if (this.myChart && this.isHighChart) {
						this.updateData();
					}
				},
				deep: true,
				immediate: true
			}
		},
		computed: {
			...mapState({
				globalEventList: state => state.event.globalEventList,
				sendCompIds: state => state.event.sendCompIds,
				eventCompIds: state => state.event.eventCompIds,
				currentEventParams: state => state.event.currentEventParams,
				globalVariable: state => state.globalVariable,
				compsList: state => state.compsList
			}),
			...mapGetters(['rceiveDataComps']),
			count() {
				return this.option.count;
			},
			dataAppend() {
				return this.option.dataAppend;
			},
			dataChartLen() {
				return (this.dataChart || []).length;
			},
			switchTheme() {
				return this.vaildData(this.option.switchTheme, false);
			},
			name() {
				let className = this.$el.className.split(' ')[0];
				const result = className.replace(config.name, '');
				return result;
			},
			minWidth() {
				const val = this.option.minWidth;
				if (val > this.width) return val;
			},
			isApi() {
				return this.dataType === 1;
			},
			isSql() {
				return this.dataType === 2;
			},
			styleChartName() {
				const obj = {
					width: setPx(this.minWidth || this.width),
					height: setPx(this.height),
					opacity: this.component.opacity || 1,
					transform: `scale(${this.component.scale || 1}) perspective(${this.component.perspective || 500}px) rotateX(${this.component.rotateX || 0}deg) rotateY(${
						this.component.rotateY || 0
					}deg) rotateZ(${this.component.rotateZ || 0}deg)`
				};
				return obj;
			},
			styleBase() {
				return {
					top: setPx(this.top),
					left: setPx(this.left),
					width: setPx(this.width),
					height: setPx(this.height)
				};
			},
			styleSizeName() {
				return Object.assign(
					{
						width: setPx(this.width),
						height: setPx(this.height)
					},
					(() => {
						if (this.minWidth) {
							return {
								overflowX: 'auto',
								overflowY: 'hidden'
							};
						}
						return {};
					})(),
					this.styles
				);
			},
			sourceIds() {
				return [...new Set(this.globalEventList.map(global => global.compId))];
			}
		},
		async created() {
			const that = this;
			if (that.eventCompIds && that.eventCompIds.length > 0) {
				that.eventCompIds.map(eventId => {
					that.$bus.off(eventId);
					that.$bus.on(eventId, async result => {
						let { params, eventType, targetCompId, compId: sourceId, customFn } = result;
						// 查找是否有全局变量参数，将全局变量增加到url中
						for (const gkey in that.globalVariable) {
							for (const ckey in that.currentEventParams) {
								if (gkey == ckey) {
									that.globalVariable[gkey] = that.currentEventParams[gkey];
									const urlParams = new URLSearchParams(window.location.search);
									urlParams.set(gkey, that.globalVariable[gkey]);
									const newUrl = new URL(window.location);
									newUrl.search = urlParams.toString();
									history.pushState({}, '', newUrl);
								}
							}
						}
						// 接收组件实例
						let targetCompInstance = findComponentInstance(targetCompId);
						function findComponentInstance(targetCompId) {
							let el = that.container.$children.find(c => c.compsList);
							let targetDom = el.$children.find(c => c.$attrs.id.indexOf(targetCompId) > -1);
							let targetComp = targetDom.$children.find(c => c.$attrs.index == targetCompId);
							return targetComp;
						}
						if (targetCompInstance && sourceId != targetCompInstance.$attrs.index) {
							let selfComp = that.compsList.find(comp => comp.index == targetCompInstance.$attrs.index);
							switch (eventType) {
								case '1': // 控制显隐
									if (selfComp) {
										selfComp.display = !selfComp.display;
									}
									break;
								case '2': // 打开链接
									window.open(result.linkUrl, '_blank');
									break;
								case '3': // 触发回调
									that.handleEventType3(targetCompInstance, sourceId, params);
									break;
								case '4': // 自定义函数
									targetCompInstance[customFn](params);
									break;
								default:
									break;
							}
						}
					});
				});
			}
		},
		mounted() {
			const that = this;
			that.init();
			EventBus.on('receiceDataComp', data => {
				// 非接数组件的订阅组件
				if (!that.$attrs.isReceiveDataComp && that.$attrs.subscribeId && that.dataType == 5) {
					let dataFormatter = that.dataFormatter;
					let res = that.queue(dataFormatter, data);
					if (Array.isArray(res)) {
						that.dataChart.length = 0;
						if (res && res.length > 0 && res[0]) {
							for (const item of res) {
								that.dataChart.push(item);
							}
						} else {
							that.dataChart = [];
						}
					} else {
						for (const key in res) {
							that.dataChart[key] = res[key];
						}
					}
					if (that.isChart) {
						that.updateChart && that.updateChart();
					}
				}
			});
		},
		beforeDestroy() {
			clearInterval(this.checkChart);
			this.$bus.offAll();
		},
		methods: {
			/**
			 *事件-回调参数-处理
			 * @param {*} SELF
			 * @param {*} sourceId
			 * @param {*} params
			 */
			async handleEventType3(SELF, sourceId, params) {
				const that = this;
				if (!SELF.isApi && !SELF.isSql && that.sourceIds.includes(sourceId)) {
					let dataChart = SELF.dataChart;
					let dataFormatter = SELF.dataFormatter;
					let res = that.queue(dataFormatter, dataChart, params);
					if (Array.isArray(res)) {
						dataChart.length = 0;
						if (res && res.length > 0 && res[0]) {
							for (const item of res) {
								dataChart.push(item);
							}
						} else {
							dataChart = [];
						}
					} else {
						for (const key in res) {
							dataChart[key] = res[key];
						}
					}
					if (SELF.isChart) {
						SELF.updateChart && SELF.updateChart();
					}
				} else if (SELF.isSql) {
					let regExp = /{{([\s\S]+?)}}/g;
					let sql = crypto.decrypt(SELF.sql);
					sql = JSON.parse(sql || '{}');
					let isDyanmicSql = regExp.test(SELF.oldSql);
					if (isDyanmicSql) {
						let sqlParams = {
							...that.currentEventParams,
							...that.globalVariable
						};
						let converterSql = await that.encryptSql(
							SELF,
							{
								id: sql.id,
								sql: SELF.oldSql
							},
							sqlParams
						);
						let newSql = crypto.decrypt(converterSql);
						newSql = JSON.parse(newSql || '{}');
						if (newSql && newSql.sql) {
							// 查询数据
							let sqlData = await that.sqlSearch(
								SELF,
								{
									id: sql.id,
									sql: newSql.sql
								},
								converterSql
							);
							SELF.dataChart = sqlData;
							if (SELF.isChart) {
								SELF.updateChart && SELF.updateChart();
							}
						} else {
							let dataType = Object.prototype.toString.call(SELF.dataChart);
							if (dataType == '[object Object]') {
								SELF.dataChart = {};
							} else if (dataType == '[object Array]') {
								SELF.dataChart = [];
							}
							if (SELF.isChart) {
								SELF.updateChart && SELF.updateChart();
							}
						}
					}
				} else if (SELF.isApi) {
					let dataQuery = typeof SELF.dataQuery === 'function' && SELF.dataQuery();
					that.apiParams = Object.assign(dataQuery, that.$route.query);
					that.oldApiParams = that.apiParams;
					// 查找出所有动态参数
					let dynamicApiParams = {};
					Object.entries(that.apiParams).forEach(obj => {
						if (/^:/.test(obj[1])) {
							dynamicApiParams[obj[0]] = obj[1];
						}
					});
					let isDynamicApiParams = Object.keys(dynamicApiParams).length > 0;
					// 动态参数API处理
					if (isDynamicApiParams) {
						let newDynamicApiParams = JSON.parse(JSON.stringify(dynamicApiParams));
						for (const key in dynamicApiParams) {
							for (const pKey in that.currentEventParams) {
								if (dynamicApiParams[key].substr(1) == pKey) {
									console.log('pKey', pKey);
									newDynamicApiParams[key] = that.currentEventParams[pKey];
								}
							}
						}
						for (const key in newDynamicApiParams) {
							if (/^:/.test(newDynamicApiParams[key])) {
								newDynamicApiParams[key] = '';
							}
						}
						that.apiParams = Object.assign(that.apiParams, newDynamicApiParams);
						let result = await that.ajaxQuery(SELF.url);
						let apiData = that.queue(SELF.dataFormatter, result);
						SELF.dataChart = apiData;
					} else {
						let result = await that.ajaxQuery(SELF.url);
						let apiData = that.queue(SELF.dataFormatter, result);
						SELF.dataChart = apiData;
					}
					if (SELF.isChart) {
						SELF.updateChart && SELF.updateChart();
					}
				}
			},
			ajaxQuery(url) {
				let hostname = window.location.hostname;
				let prefixUrl = '';
				const that = this;
				let website = {
					clientId: 'saber', // 客户端id
					clientSecret: 'saber_secret' // 客户端密钥
				};
				let headers = {
					Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`,
					'Blade-Auth': that.$route.query.token
				};
				if (hostname === 'localhost') {
					prefixUrl = `http://192.168.1.199:8000/`;
				} else {
					prefixUrl = `http://${hostname}:8000/`;
				}
				console.log('apiUrl', prefixUrl, url);
				for (const key in that.apiParams) {
					if (key == 'token') {
						delete that.apiParams[key];
					}
					if (key.startsWith('$')) {
						delete that.apiParams[key];
					}
				}
				// 删除tenantId，siteId，userId
				delete that.apiParams['siteId'];
				delete that.apiParams['tenantId'];
				delete that.apiParams['userId'];
				if (that.dataMethod == 'post') {
					return new Promise((resolve, reject) => {
						axios({
							method: 'post',
							url: prefixUrl + url,
							headers: headers,
							data: that.apiParams
						}).then(res => {
							if (res.status == 200) {
								resolve(res.data.data);
							} else {
								reject(res.data.msg);
							}
						});
					});
				} else {
					return new Promise((resolve, reject) => {
						axios({
							method: 'get',
							url: prefixUrl + url,
							headers: headers,
							params: that.apiParams
						}).then(res => {
							if (res.status == 200) {
								resolve(res.data.data);
							} else {
								reject(res.data.msg);
							}
						});
					});
				}
			},
			// 加密sql
			async encryptSql(self, sql, params) {
				const that = this;
				let regSql = /\{\{(.+?)\}\}/g;
				let regExp = /{{([\s\S]+?)}}/g;
				that._templateSettings.interpolate = regExp;
				params = Object.assign(params, self.queryParams);
				sql.sql = that.judgeSql(sql.sql, params);

				let sqlMatch = sql.sql.match(regSql);
				let dyanmicSqlParams = null;
				if (sqlMatch && sqlMatch.length > 0) {
					dyanmicSqlParams = sqlMatch.map(param => {
						return param.replace(/\{|\}/g, '');
					});
				}
				let compiled = that._template(sql.sql);

				try {
					sql.sql = compiled(params);
					return crypto.encrypt(JSON.stringify(sql));
				} catch (error) {
					return {
						code: 400,
						dataType: that.formatterDataType(that.data),
						error: that.errorTips(params, dyanmicSqlParams)
					};
				}
			},
			// 将if sql中有 <if test=customerName>  and mp.name = {{customerName}}  </if>
			judgeSql(sql, params) {
				let ifRegExp = /<if test.*>/g;
				let judgeDyanmicSql = ifRegExp.test(sql);
				// 动态判断参数
				let judgeParamsObj = {};
				if (judgeDyanmicSql) {
					let reg1 = /<if test.*>/g;
					let reg2 = /<if.*<\/if>/g;
					sql.replace(reg1, function (c) {
						let param = c.split('test = ')[1].split('>')[0];
						judgeParamsObj[param] = false;
					});
					sql = sql.replace(reg2, function (c) {
						let judgeParam = c.split('test = ')[1].split('>')[0].trim();
						// 真值 保留
						Object.keys(params).forEach(param => {
							Object.keys(judgeParamsObj).forEach(jParam => {
								if (param == jParam) {
									let cParam = params[param];
									if (cParam === null || cParam === '' || cParam === undefined) {
										judgeParamsObj[param] = false;
									} else {
										judgeParamsObj[param] = true;
									}
								}
							});
						});
						if (judgeParamsObj[judgeParam]) {
							let reg = /<[^<>]*>/g;
							c = c.replace(reg, '');
							return c;
						} else {
							return ''; // 假值 全删
						}
					});
				}
				return sql;
			},
			formatterDataType(data) {
				let type = Object.prototype.toString.call(data);
				switch (type) {
					case '[object Array]':
						return [];
					case '[object Object]':
						return {};
					default:
						break;
				}
			},
			errorTips(params, dyanmicSqlParams) {
				return `${this.$attrs.name}：${this.$attrs.index},请仔细检查其事件参数:${Object.keys(params)}和动态sql:${dyanmicSqlParams}`;
			},
			sqlSearch(self, sql, converterSql) {
				let data = null;
				let regExp = /{{([\s\S]+?)}}/g;
				const that = this;
				let isParamFreeSql = regExp.test(sql.sql);
				if (isParamFreeSql) {
					console.warn('过滤掉有参数的sql请求');
					return false;
				}
				return new Promise(resolve => {
					self.sqlFormatter(converterSql, self.$attrs.index.slice(0, 6)).then(res => {
						if (res && res.data && res.data.code == 200) {
							let result = res.data.data;
							// 静态数据
							if (Object.prototype.toString.call(self.dataFormatter) === '[object Array]') {
								let query = that.queue(self.dataFormatter, result);

								if (JSON.stringify(query) == '{}') {
									data = result;
								} else {
									data = query;
								}
							} else {
								data = result;
							}
							resolve(data);
						} else {
							resolve({
								code: res.data.code,
								message: res.data.msg
							});
						}
					});
				});
			},
			// 串行处理数据过滤函数
			queue(fnArr, data, callback) {
				if (fnArr && fnArr.length > 0) {
					return fnArr.reduce(
						(pre, cur) => {
							data = funEval(cur.code)(data, callback);
							return data;
						},
						() => {}
					);
				} else {
					return data;
				}
			},
			init() {
				this.className = `animated ${this.component.animated || ''}`;
				const main = this.$refs[this.id];
				if (main) {
					this.isChart = config.echart.includes(this.name);
					this.isHighChart = config.Highcharts.includes(this.name);
					if (this.isChart) this.myChart = window.echarts.init(main, this.theme);
					if (this.name == 'datav') {
						this.isChart = true;
						this.updateData();
					}

					if (this.isHighChart) {
						if (this.myChart) {
							this.myChart.destroy();
						}
						this.myChart = window.Highcharts.chart(main, {});
					}
				}
			},
			getItemRefs() {
				let refList = this.$parent.$parent.$refs;
				let result = {};
				Object.keys(refList).forEach(ele => {
					if (ele.indexOf(COMMON.NAME) !== -1) {
						result[ele.replace(COMMON.NAME, '')] = refList[ele][0];
					}
				});
				return result;
			},
			updateClick(params) {
				let refList = this.getItemRefs();
				let indexList = this.child.index;
				let indexName = this.child.paramName;
				if (validatenull(indexName) && validatenull(indexList)) return;
				let p = {};
				p[indexName] = params.value;
				Object.keys(refList).forEach(ele => {
					if (indexList.includes(ele)) refList[ele].updateData(p);
				});
			},
			updateAppend(result) {
				if (this.validatenull(this.appendObj)) {
					this.appendList = result;
					this.appendObj = result[0];
				} else {
					let appendList = [];
					for (let i = 0; i < result.length; i++) {
						const ele = result[i];
						if (ele.id === this.appendObj.id) break;
						else appendList.push(ele);
					}
					this.appendObj = result[0];
					appendList.reverse().forEach(ele => {
						this.appendList.unshift(ele);
					});
				}
				if (this.validatenull(this.appendCheck)) {
					this.appendCheck = setInterval(() => {
						let length = this.appendList.length - 1;
						if (length >= 0) {
							let obj = this.appendList.splice(length, 1)[0];
							this.dataChart.unshift(obj);
							let len = this.dataChart.length;
							if (len > this.count) {
								this.appendList.splice(len - 1, 1);
							}
						}
					}, 2000);
				}
			},
			updateUrl(url) {
				this.dataUrl = url;
				this.updateData();
			},
			// 更新数据核心方法
			updateData(p = {}) {
				const that = this;
				that.dynamicQuery = Object.assign(that.dynamicQuery, p);
				//根据条件查询sql或api,目前考虑配置动态模板sql/api，在跳转时进行sql/api参数赋值进行查询
				// eg: ` select * from table where createData= ${createData} `,获取路由传递的参数时，可使用lodash中template function进行赋值之后在进行sql 查询
				//获取从外部项目路由传递的参数，目前使用Base64加密，可以使用这个路由参数进行动态SQL的拼接或者api查询的传参
				return new Promise(resolve => {
					that.resetData && that.resetData();
					if (that.key) return;
					that.key = true;

					const callback = async () => {
						that.key = false;
						const bindEvent = () => {
							if (that.isChart) {
								that.updateChart();
							}
							if (that.isHighChart) {
								that.updateChart();
							}
							// if (that.myChart) that.bindClick();
							if (typeof that.stylesFormatter === 'function') {
								that.dataChart = that.stylesFormatter(that.dataChart, that.dynamicQuery, that.getItemRefs()) || {};
							}
							resolve(that.dataChart);
						};

						// 串行处理数据过滤函数
						function queue(fnArr, data, callback) {
							return fnArr.reduce(
								(pre, cur) => {
									data = funEval(cur.code)(data, callback);
									return data;
								},
								() => {}
							);
						}
						// 动态数据
						if (that.isApi) {
							const detail = res => {
								// 处理返回的数据
								that.dataAxios = res;
								let result = (() => {
									if (Object.prototype.toString.call(that.dataFormatter) === '[object Array]') {
										let query = queue(that.dataFormatter, res.data);
										if (JSON.stringify(query) == '{}') {
											return res.data;
										} else {
											return query;
										}
									}
									return res.data || {};
								})();
								// 延迟效果数据逐步增加
								if (that.dataAppend) {
									that.updateAppend(result);
								} else {
									that.dataChart = result;
								}
								bindEvent();
							};
							let compId = that.$attrs.index;
							let result = getUrlParams(that.dataUrl);
							let url = result.url;
							if (that.validatenull(url)) return;
							let dataQuery = typeof that.dataQuery === 'function' && that.dataQuery(result);
							let dataHeader = (typeof that.dataHeader === 'function' && that.dataHeader(result)) || {};
							that.apiParams = Object.assign(result.params, dataQuery, that.propQuery, that.dynamicQuery, that.$route.query, that.oldApiParams);
							that.oldApiParams = that.apiParams;
							// 查找出所有动态参数
							let dynamicApiParams = {};
							Object.entries(that.apiParams).forEach(obj => {
								if (/^:/.test(obj[1])) {
									dynamicApiParams[obj[0]] = obj[1];
								}
							});
							let isDynamicApiParams = Object.keys(dynamicApiParams).length > 0;
							// 交互动态参数API处理
							if (isDynamicApiParams) {
								let newDynamicApiParams = JSON.parse(JSON.stringify(dynamicApiParams));
								if (that.sendCompIds && that.sendCompIds.length > 0) {
									that.sendCompIds.map(sendId => {
										that.$bus.off(sendId + ':' + compId);
										that.$bus.on(sendId + ':' + compId, result => {
											let { params } = result;
											that.params = params;
											for (const key in dynamicApiParams) {
												for (const pKey in that.params) {
													if (dynamicApiParams[key].substr(1) == pKey) {
														newDynamicApiParams[key] = that.params[pKey];
													}
												}
											}
											that.apiParams = Object.assign(that.apiParams, newDynamicApiParams);

											let [baseUrl, suffix] = that.dataUrl.split('?');
											let suffixArray = [];
											if (suffix && baseUrl) {
												suffix.split('&').forEach(sub => {
													if (sub.includes('=:')) {
														let [key] = sub.split('=:');
														let str = [key, newDynamicApiParams[key]].join('=');
														suffixArray.push(str);
													} else {
														suffixArray.push(sub);
													}
												});
												that.dataUrl = baseUrl + '?' + suffixArray.join('&');
											}
											ajax();
										});
									});
								}
							} else {
								ajax();
							}

							function ajax() {
								let hostname = window.location.hostname;
								let prefixUrl = '';
								let website = {
									clientId: 'saber', // 客户端id
									clientSecret: 'saber_secret' // 客户端密钥
								};
								// TODO:全局看板请求头
								let headers = {
									...dataHeader,
									Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`,
									'Blade-Auth': that.$route.query.token
								};

								if (hostname === 'localhost') {
									prefixUrl = `http://192.168.1.199:8000/`;
								} else {
									prefixUrl = `http://${hostname}:8000/`;
								}
								for (const key in that.apiParams) {
									if (key == 'token') {
										delete that.apiParams[key];
									}
									if (key.startsWith('$')) {
										delete that.apiParams[key];
									}
								}
								// 删除tenantId，siteId，userId
								delete that.apiParams['siteId'];
								delete that.apiParams['tenantId'];
								delete that.apiParams['userId'];
								if (that.dataMethod == 'post') {
									axios({
										method: 'post',
										url: prefixUrl + url,
										headers: headers,
										data: that.apiParams
									}).then(res => {
										if (res.status == 200) {
											detail(res.data);
										} else {
											console.error(res.data.msg);
										}
									});
								} else {
									axios({
										method: 'get',
										url: prefixUrl + url,
										headers: headers,
										params: that.apiParams
									}).then(res => {
										if (res.status == 200) {
											detail(res.data);
										} else {
											console.error(res.data.msg);
										}
									});
								}
							}
						} else if (that.isSql) {
							if (typeof that.sql == 'string') {
								let sql = JSON.parse(crypto.decrypt(that.sql));
								that.oldSql = that.oldSql || sql.sql; // 带有{{}}的原来sql

								let regExp = /{{([\s\S]+?)}}/g;
								let regSql = /\{\{(.+?)\}\}/g;

								that._templateSettings.interpolate = regExp;
								// //如果有传递参数需要动态赋值参数
								let isDyanmicSql = regExp.test(that.oldSql);

								if (!sql.id) {
									that.dataChart = {
										code: 200,
										message: '请先选择数据源！'
									};
									bindEvent();
								}
								if (!sql.sql) {
									that.dataChart = {
										code: 200,
										message: '请先输入sql语句！'
									};
									bindEvent();
								}
								// 标准化sql处理
								if (!isDyanmicSql) {
									that.sql = await encryptSql.call(that, sql, {});
									// 查询数据
									that.dataChart = await sqlSearch.call(that, sql);
									bindEvent();
								} else {
									try {
										let sqlParams = {
											...that.currentEventParams,
											...that.globalVariable
										};
										// 动态参数sql处理
										let testSql = await encryptSql.call(
											that,
											{
												id: sql.id,
												sql: that.oldSql
											},
											sqlParams
										);

										if (typeof testSql == 'object') {
											that.dataChart = testSql.dataType;
											GzLog(2, testSql.error, that.$attrs.name);
										} else {
											that.sql = testSql;
											// 查询数据
											that.dataChart = await sqlSearch.call(that, sql);
										}
										bindEvent();
									} catch (error) {
										console.log(error);
									}
								}
								// 加密sql
								function encryptSql(sql, params) {
									params = Object.assign(params, that.queryParams);
									sql.sql = judgeSql(sql.sql, params);

									let sqlMatch = sql.sql.match(regSql);
									let dyanmicSqlParams = null;
									if (sqlMatch && sqlMatch.length > 0) {
										dyanmicSqlParams = sqlMatch.map(param => {
											return param.replace(/\{|\}/g, '');
										});
									}
									let compiled = that._template(sql.sql);
									try {
										sql.sql = compiled(params);
										return crypto.encrypt(JSON.stringify(sql));
									} catch (error) {
										return {
											code: 400,
											dataType: formatterDataType(that.data),
											error: errorTips(params, dyanmicSqlParams)
										};
									}
								}
								// 将if sql中有 <if test=customerName>  and mp.name = {{customerName}}  </if>
								function judgeSql(sql, params) {
									let ifRegExp = /<if test.*>/g;
									let judgeDyanmicSql = ifRegExp.test(sql);
									// 动态判断参数
									let judgeParamsObj = {};
									if (judgeDyanmicSql) {
										let reg1 = /<if test.*>/g;
										let reg2 = /<if.*<\/if>/g;
										sql.replace(reg1, function (c) {
											let param = c.split('test = ')[1].split('>')[0];
											judgeParamsObj[param] = false;
										});
										sql = sql.replace(reg2, function (c) {
											let judgeParam = c.split('test = ')[1].split('>')[0].trim();
											// 真值 保留
											Object.keys(params).forEach(param => {
												Object.keys(judgeParamsObj).forEach(jParam => {
													if (param == jParam) {
														let cParam = params[param];
														if (cParam === null || cParam === '' || cParam === undefined) {
															judgeParamsObj[param] = false;
														} else {
															judgeParamsObj[param] = true;
														}
													}
												});
											});
											if (judgeParamsObj[judgeParam]) {
												let reg = /<[^<>]*>/g;
												c = c.replace(reg, '');
												return c;
											} else {
												return ''; // 假值 全删
											}
										});
									}
									return sql;
								}
								function formatterDataType(data) {
									let type = Object.prototype.toString.call(data);
									switch (type) {
										case '[object Array]':
											return [];
										case '[object Object]':
											return {};
										default:
											break;
									}
								}
								function errorTips(params, dyanmicSqlParams) {
									return `${that.$attrs.name}：${that.$attrs.index},请仔细检查其事件参数:${Object.keys(params)}和动态sql:${dyanmicSqlParams}`;
								}
								function sqlSearch(sql) {
									let data = null;
									let results;
									try {
										sql.sql = funEval(sql.sql)(that.dynamicQuery);
										//可以在此处对routerParam进行取值，来为动态sql赋值，考虑lodash中template进行解析，对sql增加${param}类似
										results = crypto.encrypt(JSON.stringify(sql));
									} catch (error) {
										results = that.sql;
									}
									return new Promise(resolve => {
										that.sqlFormatter(results, that.$attrs.index.slice(0, 6)).then(res => {
											if (res && res.data && res.data.code == 200) {
												let result = res.data.data;
												// 静态数据
												if (Object.prototype.toString.call(that.dataFormatter) === '[object Array]') {
													let query = queue(that.dataFormatter, result);

													if (JSON.stringify(query) == '{}') {
														data = result;
													} else {
														data = query;
													}
												} else {
													data = result;
												}
												resolve(data);
											} else {
												resolve({
													code: res.data.code,
													message: res.data.msg
												});
											}
										});
									});
								}
							}
						} else {
							// let compId = that.$attrs.index;
							if (Object.prototype.toString.call(that.dataFormatter) === '[object Array]') {
								let result = queue(that.dataFormatter, that.data);
								if (JSON.stringify(result) == '{}') {
									that.dataChart = that.data;
								} else {
									that.dataChart = result;
								}
							} else {
								that.dataChart = that.data;
							}
							bindEvent();
						}
					};
					that.$nextTick(() => {
						callback();
						clearInterval(that.checkChart);
						if (that.time !== 0 && that.disabled && that.autoRequest) {
							that.checkChart = setInterval(() => {
								callback();
							}, that.time * 1000);
						}
					});
				});
			},
			getLabelFormatter(name) {
				if (this.labelFormatter) {
					return this.labelFormatter(name, this.dataChart);
				}
				return name.value;
			},
			// 绑定点击事件
			bindClick() {
				const that = this;
				that.myChart && that.myChart.off('click');
				that.myChart &&
					that.myChart.on('click', e => {
						that.clickFormatter &&
							that.clickFormatter(
								{
									type: that.name,
									name: e.name,
									value: e.value && (e.value[2] || e.value),
									data: that.dataChart,
									echartEvent: e
								},
								that.getItemRefs()
							);

						that.$globalEvent({
							compId: that.$attrs.index,
							compParams: {
								type: that.name,
								name: e.name,
								value: e.value && (e.value[2] || e.value),
								data: that.dataChart,
								echartEvent: e
							},
							eventName: '点击事件',
							globalEventList: that.globalEventList
						});
					});
			},
			// 下面俩都是chart的公共的方法,就放这里面共用
			getColor(index, first) {
				const barColor = this.option.barColor || [];
				if (barColor[index]) {
					const color1 = barColor[index].color1;
					const color2 = barColor[index].color2;
					const postion = (barColor[index].postion || 0.9) * 0.01;
					if (first) return color1;
					if (color2) {
						return {
							type: 'linear',
							x: 0,
							y: 0,
							x2: 0,
							y2: 1,
							colorStops: [
								{
									offset: 0,
									color: color1 // 0% 处的颜色
								},
								{
									offset: postion,
									color: color2 // 100% 处的颜色
								}
							],
							global: false // 缺省为 false
						};
					}
					return color1;
				}
			},
			ishasprop(condition, isprop, alwaysObj) {
				return Object.assign(
					(() => {
						return condition ? isprop : {};
					})(),
					alwaysObj
				);
			}
		}
	};
})();
